<?php

declare(strict_types=1);

namespace App\Common\Modular\Administer\Serve;

use App\Common\Modular\Administer\Model\DepartmentModel;
use App\Common\Query\Query;
use Core\Basics\BasicsServe;
use Hyperf\Database\Model\Builder;
use Zms\Exception\AppException;
use Zms\Unit\Arr;

class DepartmentServe extends BasicsServe
{
    /**
     * @return MenuModel::class
     */
    public static function model(): string
    {
        return DepartmentModel::class;
    }


    /**
     * 添加后台菜单
     * @param array $values
     * @return null|DepartmentModel
     * @throws AppException
     */
    public function created(array $values): DepartmentModel|false
    {
        if (intval($values['pid']) > 0) {
            /**
             * @var DepartmentModel $parent
             */
            $parent = $this->search(['id' => $values['pid']])->first();
            if (!$parent) {
                throw new AppException('上级菜单不存在,请刷新后重试');
            }
            $values['level'] = $parent['level'] + 1;
            $values['relevance'] = [...$parent->relevance, $parent->id];
        } else {
            $values['level'] = 0;
            $values['relevance'] = [0];
        }
        return parent::created($values);
    }


    /**
     * 获取所选部门的所有部门ID
     * @param array $ids
     * @return array
     */
    public function getSubordinateDepartmentId(array $ids): array
    {
        $depall = [];
        $result = $this->search('id>0')
            ->where(function (Builder $query) use ($ids) {
                Query::FindInSetSearch($query, 'relevance', $ids);
            })
            ->orWhereIn('id', $ids)
            ->select(['id'])
            ->get()
            ->toArray();
        if (count($result) === 0) {
            return $ids;
        }
        return Arr::unique([...$depall, ...array_column($result, 'id')]);
    }
}